﻿using System.Collections.Generic;
using System.Threading;
using System;

namespace VDataAdapter.BlockingQueue
{
	/// <summary>
	/// Description of CommunicationDataQueue.
	/// </summary>
    [Serializable()]
    public class CommunicationDataQueue
    {
        public static int TIME_OUT = 3000;//3 seconds
        public Queue<CommunicationData> que = new Queue<CommunicationData>();
        Semaphore sem = new Semaphore(0, Int32.MaxValue);
        public CommunicationData get()
        {
            CommunicationData sData = null;
            try
            {
                sem.WaitOne();

                lock (que)
                {
                    return que.Dequeue();
                }
            }
            catch (Exception ex)
            {
            }
            return sData;
        }

        public void put(CommunicationData sData)
        {
            try
            {
                lock (que)
                {                    
                    que.Enqueue(sData);
                }
                sem.Release();
            }
            catch (Exception ex) { }
        }

        public int getQueueSize()
        {
            return que.Count;
        }

        public void clear()
        {
            que.Clear();
        }

        public string GetQueueItemString(CommunicationData data)
        {
            BaseObject objBaseObject = data.getBaseObjectData();
            MessageObject objMessage = (MessageObject)objBaseObject;
            return objMessage.getMsg();
        }

        public void SendStringToQueue(string msg)
        {
            MessageObject objData = new MessageObject(msg);
            DataQueue objQueue = new DataQueue();
            this.put(new CommunicationData(objData, objQueue));
        }

        public Queue<string> DequeueToStringQueue()
        {
            var result = new Queue<string>();
            while (this.getQueueSize() > 0)
            {
                result.Enqueue(GetQueueItemString(this.get()));
            }
            return result;
        }
    }
}
